var width;
var game;
var high_score;

function bind_buttons() {
	$("#new-game-button").button().click( function() {
		reset_game();
	});
	
	$("#board").click( function(e) {
		var block_id = $(e.target).attr('id');
		var x = parseInt(block_id.substring(1,2));
		var y = parseInt(block_id.substring(3,4));
		var found = game.block_click(x,y);
		if(found>0) {
			draw_board();
			//setTimeout("animate_ghosts()", 10);
			setTimeout("refresh_game()", 200);
		}
	});
}

/*function animate_ghosts() {
	$(".b0").effect("fade", {}, 300);
}*/

function refresh_game() {
	game.fix_board();
	if(draw_board()==0) {
		game.next_level();
		draw_board();
	}
	setTimeout("draw_stat()", 200);
}

function draw_stat() {
	$("#scr").text(game.score);
	$("#level").text(game.level);
	if(game.score>high_score) {
		high_score = game.score;
		try {
			widget.setPreferenceForKey(String(high_score), "high");
		}catch(e){}
	}
	$("#high_score").text(high_score);
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

function init() {
	jQuery.preLoadImages(
		"images/block0.png",
		"images/block1.png",
		"images/block2.png",
		"images/block3.png",
		"images/block4.png",
		"images/block5.png",
		"images/block6.png",
		"images/block7.png",
		"images/block8.png"
	);
	try {
		if(widget.isrotationsupported) {
			// Force portrait view mode
			widget.setDisplayPortrait();
		}
	}catch(e){}
	high_score = 0; 
	try {
		var high = widget.preferenceForKey("high");
		if(high.length>0) {
			high_score = parseInt(high);
		}
	}catch(e){
		high_score = 0;
	}
	if(high_score==null) {
		high_score = 0;
	}
	bind_buttons();
	reset_game();
}

function reset_game() {
	game = new Game();
	game.start();
	draw_board();
	draw_stat();
}

function draw_board() {
	var blocks = 0;
	var new_html = "";
	var lastBlock = -1;
	var gameOver = true;
	for(var j=0;j<10;j++) {
		for(var i=0;i<10;i++) {
			var block = game.get_block(i,j);
			new_html += "<div id='b" + i + "_" + j + "' class='b ";
			if(block>0) {
				new_html += "b" + block;
				blocks++;
				if(lastBlock>0 && block==lastBlock) {
					gameOver = false;
				} else if(j<9) {
					var downBlock = game.get_block(i,j+1);
					if(downBlock==block) {
						gameOver = false;
					}
				}
			} else if(block==0) {
				new_html += "b0";
				gameOver = false;
			}
			new_html += "'/>";
			lastBlock = block;
		}
	}
	
	if(blocks>0 && gameOver) {
		new_html += "<div id='gameover'>Game Over</div>";
	} 
	
	$("#board").html(new_html);
	return blocks;
}